package ui.login

import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import model.db.Db
import model.repository.UserRepository
import model.vo.UserSQLVo
import state.ApplicationWindowsState
import theme.EasyChatTheme

class LoginViewModel(
    val applicationWindowsState: ApplicationWindowsState,
    private val coroutineScope: CoroutineScope
) {
    val loginBtnEnable = mutableStateOf(true)
    val avatar = mutableStateOf("")
    val userAccount = mutableStateOf("")
    val userPassword = mutableStateOf("")
    val loginStateDialogShow = mutableStateOf(false)
    val loginStateDialogMsg = mutableStateOf("")

    val allUserList = mutableListOf<UserSQLVo>()

    init {
        val readString = Db.getLastLoginAccount()
        if (readString != "") {
            userAccount.value = readString
            val userSQLVo = Db.getUser(readString)//查询用户
            userPassword.value = userSQLVo?.password.toString()
            avatar.value = userSQLVo?.avatar.toString()
        }

        val allUsers = Db.getAllUser();
        if (!allUsers.isNullOrEmpty()) {
            allUsers.let { allUserList.addAll(it) }
        }
    }

    fun login(easyChatTheme: MutableState<EasyChatTheme>) {
        //开启一个协程，并指定在IO调度器上执行
        coroutineScope.launch(Dispatchers.IO,) {
            UserRepository.login(this@LoginViewModel,easyChatTheme)
        }
    }
}